package org.hxc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hxc.dao.SysUserDao;
import org.hxc.entity.SysUser;
import org.hxc.entity.SysUserRole;
import org.hxc.service.SysUserRoleService;
import org.hxc.service.SysUserService;
import org.hxc.vo.SysUserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(SysUser)表服务实现类
 *
 * @author hxc
 * @since 2024-10-28 14:31:03
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService, UserDetailsService {

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = lambdaQuery().eq(SysUser::getUsername, username).last("limit 1").one();
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();

        List<SysUserRoleVo> sysUserRoles = sysUserRoleService.selectUserRoleVoById(user.getId());
        if (CollectionUtil.isNotEmpty(sysUserRoles)){
            authorities = sysUserRoles.stream().map(sysUserRoleVo -> new SimpleGrantedAuthority(sysUserRoleVo.getRoleCode())).collect(Collectors.toList());
        }
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("123456");
        System.err.println(encode);
    }
}

